﻿
namespace TingSLsocket

open System
open System.IO
open System.Text
open Polenter.Serialization

[<Sealed>]
type CommandSerializer() =
    let _serializer = new SharpSerializer(true)
    let _memstream = new MemoryStream()
    let _header = new Header()

    member this.Serialize(cmd,parm)=
        if parm <> null then
            _memstream.Position <- 0L
            _memstream.SetLength 0L
            _serializer.Serialize(parm,_memstream)
        
            _header.Command <- cmd
            _header.Size <- int _memstream.Length

            let buffer = Array.zeroCreate<byte> (Header.BinLength + _header.Size)
            _header.Serialize(buffer,0) |> ignore

            _memstream.Position <- 0L
            _memstream.Read(buffer,Header.BinLength,_header.Size) |> ignore
            buffer
        else
            _header.Command <- cmd
            _header.Size <- 0
            let buffer = Array.zeroCreate<byte> Header.BinLength
            _header.Serialize(buffer,0) |> ignore
            buffer

    member this.Deserialize(buffer,offset,size) =
        if buffer <> null then
            _memstream.Position <- 0L
            _memstream.SetLength 0L
            _memstream.Write(buffer,offset,size)

            // deserialize also start at the current position
            // so I have to reset to 0
            _memstream.Position <- 0L
            _serializer.Deserialize(_memstream)
        else
            null

    interface IDisposable with
        member this.Dispose() =
            _memstream.Close()
